<template>
  <div class="login-page w-screen h-screen flex-center overflow-hidden m-relative box-border pt-34">
    <div class="p-10 cursor-pointer m-absolute t-4 r-4 no-drag">
      <icon-close class="text333" @click="closeApp" />
    </div>
    <div class="box-full round-10 flex-col flex-a-c">
      <div class="flex flex-a-c mb-20">
        <a-image
          width="36"
          class="mr-10"
          :preview="false"
          src="https://images.maishou88.com/admin/buyer_circle_sc/20240402/20240402192035_5045.png"
        />
        <span class="font-bold text-size-28">买手云发单</span>
      </div>
      <div class="no-drag">
        <a-tabs
          default-active-key="1"
          size="large"
          @change="
            (e) => {
              activityKey = e
            }
          "
        >
          <a-tab-pane key="1" title="密码登录">
            <a-form ref="passwordFormRef" :model="passwordForm" class="mx-auto" style="width: 84%">
              <a-form-item
                field="mobile"
                hide-label
                class="mb-10"
                :rules="[{ required: true, validator: validatorFun }]"
                :validate-trigger="['change', 'input']"
              >
                <a-input
                  placeholder="手机号"
                  size="large"
                  v-model="passwordForm.mobile"
                  allow-clear
                >
                  <template #prefix>
                    <icon-user />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item
                field="password"
                hide-label
                :rules="[{ required: true, message: '请输入密码' }]"
                :validate-trigger="['change', 'input']"
              >
                <a-input-password
                  placeholder="密码"
                  size="large"
                  v-model="passwordForm.password"
                  allow-clear
                  @pressEnter="handleSubmit"
                >
                  <template #prefix>
                    <icon-lock />
                  </template>
                </a-input-password>
              </a-form-item>
              <a-form-item field="password" hide-label>
                <a-checkbox v-model="remember">记住密码</a-checkbox>
              </a-form-item>
              <a-form-item hide-label>
                <a-button
                  type="primary"
                  size="large"
                  :loading="loginLoading"
                  long
                  @click="handleSubmit"
                  >登录</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <a-tab-pane key="2" title="验证码登录">
            <a-form ref="codeFormRef" :model="codeForm" class="mx-auto" style="width: 84%">
              <a-form-item
                field="mobile"
                hide-label
                :rules="[{ required: true, validator: validatorFun }]"
                :validate-trigger="['change', 'input']"
              >
                <a-input placeholder="手机号" size="large" v-model="codeForm.mobile" allow-clear>
                  <template #prefix>
                    <icon-user />
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item
                field="code"
                hide-label
                :rules="[{ required: true, message: '请输入验证码' }]"
                :validate-trigger="['change', 'input']"
              >
                <a-input
                  placeholder="验证码"
                  size="large"
                  class="codeInput"
                  v-model="codeForm.code"
                  @pressEnter="handleSubmit"
                  allow-clear
                >
                  <template #prefix>
                    <icon-bug />
                  </template>
                  <template #suffix>
                    <a-button
                      type="text"
                      :disabled="codeDisabled"
                      :loading="codeLoading"
                      @click.stop="getCode"
                      >{{ codeText }}</a-button
                    >
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item field="password" hide-label>
                <a-checkbox disabled class="opacity-0">记住密码</a-checkbox>
              </a-form-item>
              <a-form-item hide-label>
                <a-button
                  type="primary"
                  size="large"
                  :loading="loginLoading"
                  long
                  @click="handleSubmit"
                  >登录</a-button
                >
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
  </div>
</template>
<script setup>
import { IconClose, IconUser, IconLock, IconBug } from '@arco-design/web-vue/es/icon'
import { Message } from '@arco-design/web-vue'
const Phone = /^1[3-9]\d{9}$/
const { ipcRenderer } = window.electron
const passwordFormRef = ref()
const codeFormRef = ref()
// 记住密码
const remember = ref(true)
const activityKey = ref('1')
const codeTimer = ref()
const codeLoading = ref(false)
const loginLoading = ref(false)
const codeText = ref('获取验证码')
const codeDisabled = ref(false)
const passwordForm = reactive({
  mobile: undefined,
  password: undefined
})

const codeForm = reactive({
  mobile: undefined,
  code: undefined
})

// 手机号验证
const validatorFun = (value, cb) => {
  if (!value) {
    cb('请输入手机号')
  } else if (!Phone.test(value)) {
    cb('请输入正确的手机号')
  } else {
    cb()
  }
}

const closeApp = () => {
  window.ipcRenderer.send('appClose')
}

const userInfo = {}

// 监听WebSocket消息
ipcRenderer.on('webSocketMessage', async (event, res) => {
  if (res?.data?.wsMsgType) {
    switch (res?.data?.wsMsgType) {
      case 'sendLoginSms':
        if (res.code == 200) {
          Message.success('获取成功')
          countdown()
        } else {
          Message.error(res.message)
        }
        codeLoading.value = false
        break
      case 'passwordLogin':
      case 'smsLogin':
        if (res.code == 200) {
          Object.assign(userInfo, res.data.list)
          if (remember.value) {
            await window.ipcRenderer.invoke('storeSet', 'passwordForm', { ...passwordForm })
          } else {
            await window.ipcRenderer.invoke('storeDel', 'passwordForm')
          }
          ipcRenderer.send('sendToWebSocket', {
            accessToken: userInfo.accessToken,
            wsMsgType: 'userInfo'
          })
        } else {
          loginLoading.value = false
          Message.error(res.message)
        }
        break
      case 'userInfo':
        if (res.code == 200) {
          Object.assign(userInfo, res.data.list)
          await window.ipcRenderer.invoke('storeSet', 'userInfo', userInfo)
          window.ipcRenderer.send('afterLogin')
        } else {
          Message.error(res.message)
        }
        loginLoading.value = false
        break
    }
  }
})

// 点击登录
const handleSubmit = async () => {
  const formRef = activityKey.value == 1 ? passwordFormRef.value : codeFormRef.value
  const form = activityKey.value == 1 ? passwordForm : codeForm
  const validateResult = await formRef?.validate()
  if (validateResult) return false
  try {
    loginLoading.value = true
    if (activityKey.value == 1) {
      ipcRenderer.send('sendToWebSocket', { ...form, wsMsgType: 'passwordLogin' })
    } else {
      ipcRenderer.send('sendToWebSocket', { ...form, wsMsgType: 'smsLogin' })
    }
  } catch {
    loginLoading.value = false
  }
}

/** 倒计时 */
const countdown = () => {
  let second = 60 // 默认时间
  codeLoading.value = false // 取消加载
  codeDisabled.value = true // 禁用按钮
  codeText.value = `${second}秒` // 按钮文本
  // 判断是否存在定时器，存在则先清除
  if (codeTimer.value) {
    clearInterval(codeTimer.value)
  }
  // 开启定时器
  codeTimer.value = Number(
    setInterval(() => {
      second--
      codeText.value = `${second}秒` // 按钮文本
      if (second <= 0) {
        codeText.value = `重新获取` // 按钮文本
        codeDisabled.value = false // 启用按钮
        clearInterval(codeTimer.value) // 清除倒计时
      }
    }, 1000)
  )
}

const getCode = () => {
  codeFormRef.value?.validateField('mobile', async (valid) => {
    if (!valid) {
      codeLoading.value = true
      codeText.value = '发送中'
      ipcRenderer.send('sendToWebSocket', { mobile: codeForm.mobile, wsMsgType: 'sendLoginSms' })
    }
  })
}

onMounted(async () => {
  const passwordFormO = await window.ipcRenderer.invoke('storeGet', 'passwordForm')
  if (passwordFormO) {
    const form = passwordFormO
    passwordForm.mobile = form?.mobile
    passwordForm.password = form?.password
  }
})

// 组件销毁之前 - 生命周期
onBeforeUnmount(() => {
  clearInterval(codeTimer.value) // 清除倒计时
})
</script>
<style lang="scss" scoped>
.login-page {
  :deep(.arco-tabs-nav-tab) {
    justify-content: center;
  }
  :deep(.arco-tabs-nav::before) {
    height: 0;
  }

  :deep(.arco-tabs-tab) {
    margin: 0 50px;
  }
}
.codeInput {
  padding-right: 0 !important;
}
</style>
